package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class ReportServiceImpl implements ReportService {


    private final OrderMapper orderMapper;
    private final UserMapper userMapper;
    private final WorkspaceService workspaceService;

    public ReportServiceImpl(OrderMapper orderMapper, UserMapper userMapper, WorkspaceService workspaceService) {
        this.orderMapper = orderMapper;
        this.userMapper = userMapper;
        this.workspaceService = workspaceService;
    }

    /**
     * 统计区间营业额
     * @param begin
     * @param end
     * @return
     */
    @Transactional
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end范围内的每天日期
        List<LocalDate> datelist = new ArrayList<>();

        datelist.add(begin);

        while(!begin.equals(end)){
            //日期计算，计算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            datelist.add(begin);
        }

        List<Double> turnoverlist = new ArrayList<>();
        for(LocalDate date : datelist){
            //查询date日期对应的营业额数据，营业额是说状态为已完成的订单的合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // select sum(amount) from orders where order_time > ? and order_time <?
            // and status = 5
            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover  = orderMapper.sumByMap(map);
            turnover = turnover ==null ? 0.0 : turnover;
            turnoverlist.add(turnover);
        }

        //封装返回结果
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(datelist, ","))
                .turnoverList(StringUtils.join(turnoverlist, ","))
                .build();
    }

    @Transactional
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> datelist = new ArrayList<>();
        datelist.add(begin);
        while(!begin.equals(end)){
            //日期计算，计算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            datelist.add(begin);
        }
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : datelist) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("endTime", endTime);
            Integer totalUser = userMapper.countByMap(map);
            map.put("beginTime", beginTime);
            Integer newUser = userMapper.countByMap(map);

            totalUserList.add(totalUser);
            totalUserList.add(newUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(datelist,","))
                .totalUserList(StringUtils.join(newUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    /**
     * 统计区间订单
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> datelist = new ArrayList<>();
        datelist.add(begin);
        while(!begin.equals(end)){
            //日期计算，计算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            datelist.add(begin);
        }

        List<Integer> orderlist = new ArrayList<>();
        List<Integer> validCountList = new ArrayList<>();

        for(LocalDate date : datelist){
            //查询每天有效订单数和总条数
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer orderCount = getOrderCount(beginTime,endTime,null);
            Integer validCount =getOrderCount(beginTime,endTime,Orders.COMPLETED);

            orderlist.add(orderCount);
            validCountList.add(validCount);
        }

        //计算总数和有效总数
        Integer totalOrder = orderlist.stream().reduce(Integer::sum).get();
        Integer validOrder = validCountList.stream().reduce(Integer::sum).get();

        Double orserComplitionRate = 0.0;
        if(totalOrder!=0)
            orserComplitionRate=validOrder.doubleValue()/(totalOrder);

        return  OrderReportVO.builder()
                .dateList(StringUtils.join(datelist,","))
                .orderCountList(StringUtils.join(orderlist,","))
                .validOrderCountList(StringUtils.join(validCountList,","))
                .totalOrderCount(totalOrder)
                .validOrderCount(validOrder)
                .orderCompletionRate(orserComplitionRate)
                .build();

    }

    /**
     * 获取销量前10的菜品
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {

        //一方面要查下单的菜品细则的表，一方面要去订单表对应的status
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //todo 了解stream流用法和转换法
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime,endTime);
        List<String> names =salesTop10
                .stream()
                .map(GoodsSalesDTO::getName).collect(Collectors.toList());

        String namelist = StringUtils.join(names,",");

        List<Integer> numbers = salesTop10
                .stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        String numberlist =StringUtils.join(numbers,",");
        return SalesTop10ReportVO
                .builder()
                .nameList(namelist)
                .numberList(numberlist)
                .build();
    }


    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库并取得所有营业数据
        LocalDate datebegin = LocalDate.now().minusDays(30);
        LocalDate datend = LocalDate.now().minusDays(1);

          //.of 把Data转换成带有时分秒的数据
        BusinessDataVO businessDataVO  = workspaceService.getBusinessData(LocalDateTime.of(datebegin,LocalTime.MIN),LocalDateTime.of(datend,LocalTime.MAX));

        //2.通过POI写入数据
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板");

        try{
        XSSFWorkbook excel = new XSSFWorkbook(in);

        XSSFSheet sheet = excel.getSheet("Sheet1");
        sheet.getRow(1).getCell(1).setCellValue("时间："+datebegin+"至"+datend);

        XSSFRow row = sheet.getRow(3);
        row.getCell(2).setCellValue(businessDataVO.getTurnover());
        row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
        row.getCell(6).setCellValue(businessDataVO.getNewUsers());

        row = sheet.getRow(4);
        row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
        row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

        //填充明细
            for (int i = 0;i<30;i++){
                LocalDate date = datebegin.plusDays(i);
                BusinessDataVO businessDataVO1 =workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));
                row = sheet.getRow(i+7);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO1.getTurnover());
                row.getCell(3).setCellValue(businessDataVO1.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO1.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO1.getNewUsers());
            }
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            out.flush();

            out.close();
            excel.close();
        }catch (Exception e){

        }
        //3.通过输出流将Excel下载到客户端浏览器}
    }

    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end,Integer status) {
        Map map = new HashMap();
        map.put("beginTime", begin);
        map.put("endTime", end);
        map.put("status", status);

        return orderMapper.countByMap(map);
    }

}
